import * as vscode from "vscode";
import { programMenusProvider } from "./ProgramMenusProvider";
import { login } from "./contstants/vscode-request";

class TwsManager {

    private currentUser: User | any;
    logout() {
        this.currentUser = undefined
        vscode.window.showInformationMessage('登出成功')
        programMenusProvider.refresh()
    }
    public async login() {
        if (this.currentUser) {
            this.logout();
            return false
        }
        const username: string | undefined = await vscode.window.showInputBox({
            prompt: "Enter username or E-mail.",
            validateInput: (s: string): string | undefined => s && s.trim() ? undefined : "The input must not be empty",
        });
        const password: string | undefined = await vscode.window.showInputBox({
            prompt: "Enter password",
            password: true,
            validateInput: (s: string): string | undefined => s && s.trim() ? undefined : "The input must not be empty",
        });
        const res = await login({ username, password })
        if (res) {
            const { jwt, sessionId, userId } = res.data
            this.currentUser = new User(jwt, sessionId, userId)
            vscode.window.showInformationMessage('登录成功')
            programMenusProvider.refresh()
            return true
        } else {
            vscode.window.showErrorMessage('登录失败，帐号或密码错误');
            return false
        }
    }

    public isLogin(): boolean {
        return !!this.currentUser
    }
    public getUser(): User | any {
        return this.currentUser
    }
}

class User {
    constructor(
        readonly jwt: string,
        readonly sessionId: string,
        readonly userId: number) { }
}

export const twsManager: TwsManager = new TwsManager()